# coding=utf-8
from flask import current_app
from flask import json
from flask import request, jsonify, make_response
from iHome import redis_store, constants
from iHome.response_code import RET
from iHome.utils.captcha.captcha import captcha
from . import api
import re
import random
from iHome.utils.sms import CCP


@api.route('/sms_code', methods=['POST'])
def send_sms_code():
    # 获取参数（手机号，图片验证码，图片验证码id)
    req_data = request.data
    req_dict = json.loads(req_data)
    mobile = req_dict.get('mobile')
    image_code = req_dict.get('image_code')
    image_code_id = req_dict.get('image_code_id')
    # 判断数据的有效性
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    if not re.match(r'^1[3456789]\d{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号格式不正确')
    try:
        real_image_code = redis_store.get('image:%s' % image_code_id)
    except Exception as e:
        current_app.logger.erroe(e)
        return jsonify(errno=RET.DATAERR, errmsg='查询图片验证码错误')
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg='图片验证码已经过期')
    if real_image_code != image_code:
        return jsonify(errno=RET.DATAERR, errmsg='图片验证码错误')
    # TODO 发送短信验证码
    # 生成短信验证码并发送
    sms_code = '%06d' % random.randint(0, 999999)
    print sms_code
    try:
        redis_store.set('sms_code:%s' % mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存验证码失败')
    # res = CCP().sendTemplateSMS(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], 1)
    # if res != 1:
    #     return jsonify(errno=RET.THIRDERR, errmsg='发送短信失败')
    return jsonify(errno=RET.OK, errmsg='发送短信成功')


# 提供图片验证码
@api.route('/image_code')
def get_image_code():
    # 获取uuid验证码
    cur_id = request.args.get('cur_id')
    # 生成图片验证码
    name, text, data = captcha.generate_captcha()
    print text
    # 在redis中存储验证码文本，以便于后续的验证
    try:
        redis_store.set('image:%s' % cur_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        # print e
        return jsonify(errno=RET.DATAERR, errmsg='保存图片失败')
    # print text
    response = make_response(data)
    response.headers['Content-Type'] = 'image/jpg'
    return response
